import 'package:flutter_module/tabbar/shop/shopModel.dart';
import 'package:dio/dio.dart';
import 'package:flutter_module/request/NetRequest.dart';
import 'package:flutter_module/tabbar/shop/deviceModel.dart';
import 'package:flutter_module/tool/userManager.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:flutter_module/tool/fileManager.dart';
import 'package:flutter_module/tabbar/shop/shopTagModel.dart';
import 'package:flutter_module/tabbar/shop/areaModel.dart';

class ShopDeviceManager {
  
  static List<String> initials = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','#'];
  

  /// 获取按门店首字母排序后的门店和设备
  static Future fetchAllSortShopsDevice() async {

    Map<String,ShopModel> shopModels = await fetchAllShopDevice();

    return sortShops(shopModels);
  }

  /// 获取所有门店和设备
  static Future fetchAllShopDevice() async{
    Map<String,ShopModel> shopModels = {};

    Map<String,ShopModel> collectionShopModels = await _fetchCollectionsShops();

    List shopsList = await _fetchShopsList();
    shopsList.forEach((val) {
      ShopModel model = ShopModel.fromJson(val);
      Map<String,StoreTag> storeTagMap = {};
      if (model.storeTags != null) {
        model.storeTags.forEach((tag){
          if (tag.uuid.length > 0) {
            storeTagMap[tag.uuid] = tag;
          }
        });
      }
      
      model.storeTagMap = storeTagMap;
      String pinyin = PinyinHelper.getShortPinyin(model.name);
      String initial = pinyin.substring(0,1).toUpperCase();
      if (!initials.contains(initial)) {
        initial = '#';
      }
      model.initial = initial;
      if (model.uuid.length > 0) {
        if (collectionShopModels[model.uuid] != null) {
          model.isCollection = true;
        }
        shopModels[model.uuid] = model;
      }
    });

    List devicesList = await _fetchDevicesList();
    // 将设备信息保存到磁盘
    await FileManager.saveDevicesString(devicesList);
    devicesList.forEach((val){
      DeviceModel model = DeviceModel.fromJson(val);
      if (shopModels[model.storeId] != null) {
        ShopModel shopModel = shopModels[model.storeId];
        shopModel.devices.add(model);
      }
    });

    return shopModels;
  }

  static Future _fetchShopsList() async {
  
    Response response;
    NetRequest dio = NetRequest();
    String url = 'stores/list';
    response = await dio.get(url);
    return response.data;
  }

  static Future _fetchDevicesList() async {
    Response response;
    NetRequest dio = NetRequest();
    String url = 'devices';
    response = await dio.get(url,queryParameters: {"page":0,"size":10000});
    return response.data['content'];
  }

  static Future _fetchCollectionsShops() async {
    Response response;
    NetRequest dio = NetRequest();
    String url = 'stores/collections';
    response = await dio.get(url);

    Map<String,ShopModel> shopModels = {};
    List responseList = [];
    if (response.data is List) {
      responseList = response.data;
    }
    
    responseList.forEach((val){
      ShopModel model = ShopModel.fromJson(val);
      String pinyin = PinyinHelper.getShortPinyin(model.name);
      String initial = pinyin.substring(0,1).toUpperCase();
      if (!initials.contains(initial)) {
        initial = '#';
      }
      model.initial = initial;
      if (model.uuid.length > 0) {
        shopModels[model.uuid] = model;
      }
    });

    return shopModels;
  }

  /// 获取收藏门店
  static Future fetchCollectionShops() async {
    Response response;
    NetRequest dio = NetRequest();
    String url = 'stores/collections';
    response = await dio.get(url);

    Map<String,ShopModel> shopModels = {};
    List responseList = [];
    if (response.data is List) {
      responseList = response.data;
    }
    responseList.forEach((val) {
      ShopModel model = ShopModel.fromJson(val);
      model.isCollection = true;
      String pinyin = PinyinHelper.getShortPinyin(model.name);
      String initial = pinyin.substring(0,1).toUpperCase();
      if (!initials.contains(initial)) {
        initial = '#';
      }
      model.initial = initial;
      if (model.uuid.length > 0) {
        shopModels[model.uuid] = model;
      }
      
    });

    List<DeviceModel> devicesList = await FileManager.fetchDevices();
    devicesList.forEach((val){
      if (shopModels[val.storeId] != null) {
        ShopModel shopModel = shopModels[val.storeId];
        shopModel.devices.add(val);
      }
    });

    return sortShops(shopModels);
  }

  static List<ShopSortModel> sortShops(Map<String,ShopModel> shopModels){

    Map<String,List<ShopModel>> shopsMap = {};
    shopModels.forEach((key,val){
      if (shopsMap[val.initial] == null) {
        List<ShopModel> list = [];
        list.add(val);
        shopsMap[val.initial] = list;
      }else{
        List<ShopModel> list = shopsMap[val.initial];
        list.add(val);
      }
    });

    List<String> initials = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','#'];
    List<ShopSortModel> shopSortModels =[];
    initials.forEach((val){
      if (shopsMap[val] != null) {
        ShopSortModel model = ShopSortModel();
        model.initial = val;
        model.shops = shopsMap[val];
        shopSortModels.add(model);
      }
    });

    return shopSortModels;

  }

  /// 添加收藏门店
  static Future additionCollectionShop(String shopUUID) async {
    Response response;
    NetRequest dio = NetRequest();
    String url = 'stores/collection/' + shopUUID;
    response = await dio.post(url);

    return response;
  }

  /// 删除收藏门店
  static Future deleteCollectionShop(String shopUUID) async {
    Response response;
    NetRequest dio = NetRequest();
    String url = 'stores/collection/' + shopUUID;
    response = await dio.delete(url);

    return response;
  }

  /// 获取门店标签
  static Future fetchShopTags() async {

    Map<String,ShopModel> shopModels = await fetchAllShopDevice();

    Response response;
    NetRequest dio = NetRequest();
    String url = 'store_tag?size=1000&page=0';
    response = await dio.get(url);
    List contentList = [];
    List<ShopTagModel> shopTags = [];
    if (response.data['content'] is List) {
      contentList = response.data['content'];
      contentList.forEach((val){
        ShopTagModel tagModel = ShopTagModel.fromJson(val);
        
        shopModels.forEach((shopUUID,shopModel){
          if (shopModel.storeTagMap.keys.contains(tagModel.uuid)) {
            tagModel.tagShops.add(shopModel);
          }
        });
        shopTags.add(tagModel);
      });
    }

    return shopTags;
  }

  /// 获取区域树
  static Future fetchAreaTree() async {

    Map<String,ShopModel> shopModels = await fetchAllShopDevice();

    Map<String,List<ShopModel>> areaMap = {};
    shopModels.forEach((key,value){
      if (areaMap[value.groupId] == null) {
        List<ShopModel> shops = [];
        shops.add(value);
        areaMap[value.groupId] = shops;
      }else{
        List<ShopModel> shops = areaMap[value.groupId];
        shops.add(value);
      }
    });

    Response response;
    NetRequest dio = NetRequest();
    String url = 'store_groups/tree';
    response = await dio.get(url);

    AreaModel rootAreaModel = AreaModel();
    Context context = Context();
    rootAreaModel.context = context;
    rootAreaModel.context.name = UserManager().userInfo.enterprise.abbrName;
    rootAreaModel.children = parseAreaTree(response.data,areaMap);

    return rootAreaModel;
  }

  static List<AreaModel> parseAreaTree(List list,Map<String,List<ShopModel>> areaMap){

    List<AreaModel> areaModels = [];
    for (var map in list) {
      AreaModel model = AreaModel.fromJson(map);

      if (areaMap[model.context.uuid] != null) {
        List<ShopModel> shops = areaMap[model.context.uuid];
        model.shops.addAll(shops);
      }

      if (map['children'].length > 0) {
        model.children = parseAreaTree(map['children'],areaMap);
      }

      areaModels.add(model);
    }

    return areaModels;

  }

}